"""
FFmpeg插件

提供FFmpeg视频处理功能的插件实现。
"""

import asyncio
from typing import Any, Dict, List

from src.core.plugin import ProcessorPlugin
from src.core.di import Inject
from src.modules.processors import FFmpegProcessor
# from src.core.ast import Ast, AstContext  # 暂时注释掉，因为AstContext未定义

class FFmpegPlugin(ProcessorPlugin):
    """
    FFmpeg插件
    
    集成FFmpeg处理器到插件系统中。
    """
    
    def __init__(self):
        super().__init__()
        self.processor: FFmpegProcessor = None
    
    @property
    def name(self) -> str:
        return "FFmpegPlugin"
    
    @property
    def version(self) -> str:
        return "1.0.0"
    
    @property
    def description(self) -> str:
        return "基于FFmpeg的视频处理插件"
    
    @property
    def author(self) -> str:
        return "MixVideo Team"
    
    @property
    def dependencies(self) -> List[str]:
        return []
    
    def get_supported_operations(self) -> List[str]:
        return ["slice", "transcode", "extract_info", "extract_thumbnails"]
    
    async def on_init(self, ctx: Any) -> None:
        """初始化插件"""
        
        # 从依赖注入容器获取FFmpeg处理器
        from src.core.di import injector
        
        try:
            self.processor = injector.get(FFmpegProcessor)
        except Exception:
            # 如果没有注册，创建新实例
            config = ctx.get_global_config("ffmpeg", {})
            logger = ctx.get_logger(self.name)
            self.processor = FFmpegProcessor(config={"ffmpeg": config}, logger=logger)
        
    
    def on_compiler(self, ast: Any, ctx: Any) -> Any:
        """编译时处理"""
        # 暂时简化实现
        return ast

    def on_execute(self, ast: Any, ctx: Any) -> Any:
        """执行时处理"""
        # 暂时简化实现
        return ctx
    
    async def process(self, input_data: Any, **kwargs) -> Any:
        """处理数据"""
        if not self.processor:
            raise RuntimeError("FFmpeg处理器未初始化")
        
        operation = kwargs.get('operation', 'slice')
        return await self.processor.process(input_data, operation, **kwargs)
    
    async def classify(self, input_data: Any, **kwargs) -> Any:
        """分类数据（不适用于FFmpeg插件）"""
        raise NotImplementedError("FFmpeg插件不支持分类功能")
    
    async def output(self, data: Any, **kwargs) -> Any:
        """输出数据（不适用于FFmpeg插件）"""
        raise NotImplementedError("FFmpeg插件不支持输出功能")
    
    def _execute_ffmpeg_slice(self, ast: Any, ctx: Any) -> Dict[str, Any]:
        """执行FFmpeg切片"""
        if not self.processor:
            raise RuntimeError("FFmpeg处理器未初始化")
        
        # 获取参数
        input_path = getattr(ast, 'input_path', ctx.get_data('input_path'))
        output_path = getattr(ast, 'output_path', ctx.get_data('output_path', './output'))
        max_duration = getattr(ast, 'max_duration', 30)
        min_duration = getattr(ast, 'min_duration', 3)
        quality = getattr(ast, 'quality', 'medium')
        scene_detection = getattr(ast, 'scene_detection', True)
        
        if not input_path:
            raise ValueError("未指定输入视频路径")
        
        # 异步执行切片
        async def slice_task():
            return await self.processor.slice_video(
                input_path=input_path,
                output_dir=output_path,
                max_duration=max_duration,
                min_duration=min_duration,
                quality=quality,
                scene_detection=scene_detection
            )
        
        # 在事件循环中运行
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                # 如果已经在事件循环中，创建任务
                task = asyncio.create_task(slice_task())
                # 这里需要等待任务完成，但不能在同一个事件循环中await
                # 实际实现中应该使用适当的异步处理方式
                result = []  # 临时返回空结果
            else:
                result = loop.run_until_complete(slice_task())
        except RuntimeError:
            # 没有事件循环，创建新的
            result = asyncio.run(slice_task())
        
        # 更新上下文数据
        ctx.set_data('video_slices', result)
        ctx.set_data('slice_count', len(result))
        
        return {
            'input_path': input_path,
            'output_slices': result,
            'slice_count': len(result)
        }
    
    async def on_destroy(self) -> None:
        """销毁插件"""
        self.processor = None


# 插件元数据
PLUGIN_METADATA = {
    "name": "FFmpegPlugin",
    "version": "1.0.0",
    "description": "基于FFmpeg的视频处理插件",
    "author": "MixVideo Team",
    "email": "team@mixvideo.com",
    "category": "processor",
    "tags": ["video", "ffmpeg", "processing"],
    "dependencies": [],
    "permissions": ["file_read", "file_write", "process_execute"],
    "config_schema": {
        "ffmpeg": {
            "type": "object",
            "properties": {
                "binary_path": {
                    "type": "string",
                    "default": "ffmpeg",
                    "description": "FFmpeg可执行文件路径"
                },
                "ffprobe_path": {
                    "type": "string", 
                    "default": "ffprobe",
                    "description": "FFprobe可执行文件路径"
                },
                "quality_presets": {
                    "type": "object",
                    "description": "质量预设配置"
                }
            }
        }
    },
    "default_config": {
        "ffmpeg": {
            "binary_path": "ffmpeg",
            "ffprobe_path": "ffprobe",
            "quality_presets": {
                "low": {"crf": "28", "scale": "640:360"},
                "medium": {"crf": "23", "scale": "1280:720"},
                "high": {"crf": "18", "scale": "1920:1080"}
            }
        }
    }
}

# 插件类
PLUGIN_CLASS = FFmpegPlugin
